package util;

import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.Game;
import org.newdawn.slick.Music;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.util.Log;

/**A fixed frames-per-second alternative to Slick2D's annoying deltatime-based game containers.
 * @author Logan
 *
 */
public class App extends AppGameContainer
{
	private long last=System.nanoTime(),current=System.nanoTime(),remain=0;
	private long frameTime=(long)1000000000.0/60;
	private static final int MAX_SKIP=10;
	
	public App(Game game) throws SlickException
	{
		super(game);
		super.setVSync(true);
	}
	
	/**Sets the frames per second of the game.
	 * @param fps frames per second to set the game to.
	 */
	public void setFPS(int fps)
	{
		frameTime=(long)1000000000.0/fps;
	}
	
	protected void updateAndRender(int delta) throws SlickException
	{
		game.render(this,this.getGraphics());
		// System.out.println(delta);
		
		current=System.nanoTime();
		long dt=current-last;
		int frameNum=0;
		
		while(remain>=frameTime)
		{	
			input.poll(width, height);
			Music.poll(delta);
			
			game.update(this,-1);
			
			frameNum++;
			remain-=frameTime;
			if(frameNum>App.MAX_SKIP)
			{
				//FPS Low
				Log.warn("Low fps!");
				remain=0;
				break;	
			}
		}
		
		remain+=dt;
		last=current;
		
		if(this.isShowingFPS())
			this.getDefaultFont().drawString(10,10,"FPS: "+super.getFPS());
	}
}
